package com.wsy.security;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;

import javax.annotation.Resource;
import javax.sql.DataSource;

@Configuration
//启用认证服务器
@EnableAuthorizationServer
public class Oauth2Config extends AuthorizationServerConfigurerAdapter {

    private static final String JWT_SIGNINGKEY="back-shopping";
//    private static final String JWT_SIGNINGKEY="front-shopping";

    @Resource
    private PasswordEncoder passwordEncoder;

    @Resource
    private AuthenticationManager authenticationManager;

    @Resource
    private DataSource dataSource;


    /**
     * jwt令牌转换器：设置jwt生成token的相关配置
     * @return
     */
    @Bean
    protected JwtAccessTokenConverter jwtAccessTokenConverter(){
        JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter();
        //设置密钥
        jwtAccessTokenConverter.setSigningKey(JWT_SIGNINGKEY);
        return jwtAccessTokenConverter;
    }

    @Bean
    public TokenStore tokenStore(){
        //默认存储方式
//        return new InMemoryTokenStore();
        return new JwtTokenStore(jwtAccessTokenConverter());
    }

    /**
     * 配置认证过程：security认证
     * @param endpoints
     * @throws Exception
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        //设置tokenServices参数信息
        DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
        //允许刷新token
        defaultTokenServices.setSupportRefreshToken(true);
        //设置token存储方法
        defaultTokenServices.setTokenStore(tokenStore());
        endpoints.authenticationManager(authenticationManager)
//                .tokenServices(defaultTokenServices)
                //token转换器
                .accessTokenConverter(jwtAccessTokenConverter())
                .tokenStore(tokenStore());
    }

    /**
     * 设置哪些服务可以从oauth2中获取token
     * 在认证中心备案客户端，支持谁来获取token
     * 用来配置客户端详情服务（ClientDetailsService），客户端详情信息在这里进行初始化，
     * 能够把客户端详情信息写死在这里或者是通过数据库来存储调取详情信息
     * <p> * authorization_code：授权码类型
     * 1.授权码模式（authorization_code）
     * 2.简化模式（implicit）
     * 3.密码模式（resource owner password credentials）
     * 4.客户端模式（client_credentials）
     * 5.通过以上授权获得的刷新令牌来获取新的令牌（refresh_token）
     * @param clients
     * @throws Exception
     */
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
//        clients.inMemory()
//                // 客户端id
//                .withClient("aaa")
//                // 客户端可以访问的资源:不设置，所有的资源都可以访问
//                .resourceIds("bookinfo","demo02")
//                // 秘钥
//                .secret(passwordEncoder.encode("123"))
//                .authorizedGrantTypes("authorization-code","implicit","client_credentials","password","refresh_token")
//                // 设置token的有效期
//                .accessTokenValiditySeconds(120)
//                .scopes("all")
//                .and()
//                // 客户端id
//                .withClient("bookinfo")
//                .resourceIds("bookinfo")
//                // 秘钥
//                .secret(passwordEncoder.encode("123"))
//                .authorizedGrantTypes("authorization-code","implicit","client_credentials","password","refresh_token")
//                // 设置token的有效期
//                .accessTokenValiditySeconds(120)
//                .scopes("all");

        //使用jdbc方式获取客户端信息
        clients.jdbc(dataSource).passwordEncoder(passwordEncoder);
    }

    /**
     * 允许客户端调用Oauth2的授权接口
     * @param security
     * @throws Exception
     */
    @Override

    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        // 允许客户端访问授权接口
        security.allowFormAuthenticationForClients();
        // 允许已经授权的用户访问Oauth2的接口
        security.checkTokenAccess("permitAll()");
        security.tokenKeyAccess("isAuthenticated()");
    }
}
